package com.kele.controller;

import com.alibaba.fastjson.JSON;
import com.kele.entity.Files;
import com.kele.entity.Logs;
import com.kele.service.impl.FileServiceImpl;
import com.kele.util.FileUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Version 2019
 * @Author:kele
 * @Date:2021/4/19
 * @Content:
 * @Description： 文件上传
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileServiceImpl fileService;

    @RequestMapping("/upload")
    public Map<String,Object> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Map map=new HashMap();
        //定义要上传文件 的存放路径
        String localPath="F:/crm_upload";
        //获得文件名字
        String fileName=file.getOriginalFilename();
        //文件名=localpath+fileName
        File dest = new File(localPath + fileName);
        if(FileUploadUtil.upload(file, localPath, fileName)){
            // 将上传的文件写入到服务器端文件夹
            // 获取当前项目的完整url
            String requestURL = request.getRequestURL().toString();
            // 获取当前项目的请求路径url
            String requestURI = request.getRequestURI();
            // 得到去掉了uri的路径
            String url = requestURL.substring(0, requestURL.length()-requestURI.length() + 1);
            url= localPath+fileName;
        }
        Files files=new Files();
        files.setFile_name(fileName);
        Date date=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(date);
        files.setUpload_time(format);

        boolean b = fileService.addFile(files);
        if (b){
            map.put("success",true);
            map.put("msg","上传成功");
            return map;
        }
        map.put("success",false);
        map.put("msg","上传失败");
        return  map;
    }

    @RequestMapping("/getFiles")
    @ResponseBody
    public String getAllFiles() {
        List<Files> list = fileService.getAllFiles();
        String jsonString = JSON.toJSONString(list);
        System.out.println(jsonString);
        return jsonString;
    }
    /**
     * 文件下载
     */
    @RequestMapping("/download/{file_id}")
    public void download(@PathVariable("file_id") Integer id, HttpServletResponse response) throws IOException {
        //获得文件信息
        Files files = fileService.findById(id);
        System.out.println(files);
        //获得文件名称
        String fileName=files.getFile_name();
        //获得下载文件的具体名字
        String relName="F:/crm_upload/"+fileName;
        System.out.println(relName);
       File file=new File(relName);
       if (file.exists()){
           response.setContentType("application/force-download");
           response.addHeader("Content-Disposition", String.format("attachment; filename=\"%s\""+fileName, URLEncoder.encode(fileName, "utf-8")));
           byte[] b=new byte[1024];
           FileInputStream fis=null;
           BufferedInputStream bis=null;
           try {
               fis=new FileInputStream(file);
               bis=new BufferedInputStream(fis);
               OutputStream os=response.getOutputStream();
               int i=bis.read(b);
               while (i!=-1){
                   os.write(b,0,i);
                   i=bis.read(b);
               }

           } catch (Exception e) {
               e.printStackTrace();
           }finally {
               assert bis != null;
               bis.close();
               fis.close();
           }
       }
    }
    /**
     * 通过文件名查找文件
     */
    @RequestMapping("/getFileByFileName")
    public  String getFilesByFileName(String file_name){
        List<Files> filesList = fileService.getFileByFileName(file_name);
        String json=JSON.toJSONString(filesList);
        System.out.println(json);
        return json;
    }

    /**
     * 通过文件名模糊查找文件
     */
    @RequestMapping("/queryByKeyWord")
    public  String queryByKeyWord(String file_name){
        List<Files> filesList = fileService.queryByKeyWord(file_name);
        String json=JSON.toJSONString(filesList);
        System.out.println(json);
        return json;
    }

}
